package com.demo.rabbitmq.producer;

import com.demo.rabbitmq.config.DirectExchangeEnum;
import com.demo.rabbitmq.config.DirectRoutingKeyEnum;
import com.demo.rabbitmq.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class DirectProducer {

    @Resource
    private RabbitTemplate rabbitTemplate;

    public void send(int i) {
        String exchange = DirectExchangeEnum.DIRECT_EXCHANGE.getExchangeName();
        String routingKey = DirectRoutingKeyEnum.DIRECT_QUEUE_ROUTING_KEY.getRoutingKeyName();
        String content = String.format("消息=%d，hello world! 当前时间：%s", i, new Date());
        rabbitTemplate.convertAndSend(exchange, routingKey, content);
    }

    /**
     * 生产者发送消息增加入参CorrelationData，生成message id。在回调函数会获取CorrelationData对象
     */
    public void sendWithMessageId() {
        String exchange = DirectExchangeEnum.DIRECT_EXCHANGE.getExchangeName();
        String routingKey = DirectRoutingKeyEnum.DIRECT_QUEUE_ROUTING_KEY.getRoutingKeyName();
        User user = new User();
        user.setUserName("hello world");
        rabbitTemplate.convertAndSend(exchange, routingKey, user, new CorrelationData());
    }

    /**
     * 消息路由到一条不存在的队列，验证ReturnsCallback是否收到消息
     */
    public void sendNotExistQueue() {
        String exchange = DirectExchangeEnum.DIRECT_EXCHANGE.getExchangeName();
        String routingKey = DirectRoutingKeyEnum.DIRECT_QUEUE_ROUTING_KEY.getRoutingKeyName() + 1;
        String content = "不存在队列消息";
        User user = new User();
        user.setUserName(content);
        rabbitTemplate.convertAndSend(exchange, routingKey, user, new CorrelationData());
    }

    /**
     * 测试发送信息到非持久化队列，并且没有消费者，直到RabbitMQ服务崩溃
     */
    public void sendNotDurableQueue() {
        String exchange = DirectExchangeEnum.DIRECT_NOT_DURABLE_EXCHANGE.getExchangeName();
        String routingKey = DirectRoutingKeyEnum.DIRECT_QUEUE_NOT_DURABLE_ROUTING_KEY.getRoutingKeyName();
        for (int i = 0; i < 100000; i++) {
            String msg = "a";
            for (int j = 0; j < 10; j++) {
                msg = msg + msg;
            }
            rabbitTemplate.convertAndSend(exchange, routingKey, msg);
        }
    }

}
